from __future__ import annotations
from typing import Optional, Dict, Any
from sqlalchemy.orm import Mapped, mapped_column
from extensions import db
from datetime import datetime
import uuid
from sqlalchemy import func  # 新增导入

class Product(db.Model):
    """商品模型"""
    __tablename__ = 'products'

    # 自增主键ID，系统内部使用的唯一标识
    id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
    # 商品唯一标识符，使用UUID格式作为商品的唯一标识
    product_id: Mapped[str] = mapped_column(db.String(36), unique=True, index=True, default=lambda: str(uuid.uuid4()))
    # 商品名称
    name: Mapped[str] = mapped_column(db.String(100), nullable=False)
    # 商品价格
    price: Mapped[float] = mapped_column(db.Float, nullable=False)
    # 商品描述
    description: Mapped[Optional[str]] = mapped_column(db.Text)
    # 商品图片URL
    image_url: Mapped[Optional[str]] = mapped_column(db.String(500))
    # 提成比例（百分比，例如：15.5表示15.5%）
    commission_rate: Mapped[float] = mapped_column(db.Float, nullable=False, default=0.0)
    # 扣费类型：1-固定金额 2-比例
    charge_type: Mapped[int] = mapped_column(db.Integer, nullable=False, default=1)
    # 扣费值（根据charge_type决定是固定金额还是比例）
    charge_value: Mapped[float] = mapped_column(db.Float, nullable=False, default=0.0)
    # 记录创建时间
    created_at: Mapped[datetime] = mapped_column(
        db.DateTime,
        server_default=func.now(),
        default=datetime.utcnow
    )

    def __init__(self, name: str, price: float, description: Optional[str] = None, 
                image_url: Optional[str] = None, commission_rate: float = 0.0,
                charge_type: int = 1, charge_value: float = 0.0):
        self.name = name
        self.price = price
        self.description = description
        self.image_url = image_url
        self.commission_rate = commission_rate
        self.charge_type = charge_type
        self.charge_value = charge_value

    def to_dict(self) -> Dict[str, Any]:
        """将模型转换为字典"""
        return {
            'id': self.id,
            'product_id': self.product_id,
            'name': self.name,
            'price': self.price,
            'description': self.description,
            'image_url': self.image_url,
            'commission_rate': self.commission_rate,
            'charge_type': self.charge_type,
            'charge_value': self.charge_value,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
            'is_deleted': self.is_deleted
        }
    # 记录最后更新时间
    updated_at: Mapped[datetime] = mapped_column(
        db.DateTime,
        server_default=func.now(),  # 优先使用数据库当前时间
        default=datetime.utcnow,    # 使用Python系统时间作为后备
        onupdate=datetime.utcnow     # 更新时使用Python系统时间
    )
    # 软删除标记
    is_deleted: Mapped[bool] = mapped_column(db.Boolean, default=False)